package com.aia.ilp.web;

import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.StringUtils;

import com.aia.ilp.domain.Image;
import com.aia.ilp.service.MainService;
import com.opensymphony.xwork2.ActionSupport;

public class PicImageAction extends ActionSupport {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PicImageAction.class);

	private String mail;
	private MainService mainService;
	/**
	 * Logger for this class
	 */

	private static final long serialVersionUID = 1L;

	public String execute() throws Exception {
		FileInputStream fis = null;
		OutputStream os = null;
		Image image = null;
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("image/png");
			os = response.getOutputStream();
			
			if (StringUtils.hasText(mail)) {
				image = mainService.getImageByMail(mail);
			}

			if (image != null) {
				byte[] imgBin = image.getIMG_BIN();
				os.write(imgBin);
			} else {
				String str = ServletActionContext.getServletContext().getRealPath("/images/image.jpg");
				fis = new FileInputStream(str);
				IOUtils.copy(fis, os);
			}
		} catch (javax.imageio.IIOException iioe) {
			if (logger.isDebugEnabled()) {
				logger.debug("execute()"); //$NON-NLS-1$
			}
		} finally {
			IOUtils.closeQuietly(fis);
			if (os != null) {
				os.flush();
				IOUtils.closeQuietly(os);
			}
		}
		return null;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public String getMail() {
		return mail;
	}

	public void setMainService(MainService mainService) {
		this.mainService = mainService;
	}

	public MainService getMainService() {
		return mainService;
	}

}
